package com.javacoo.event.client.support;

import java.util.Optional;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;

import lombok.extern.slf4j.Slf4j;

/**
 * 获取applicationContext
 * <p>说明:</p>
 * <li></li>
 * @author duanyong@jccfc.com
 * @date 2021/10/16 9:28
 */
@Slf4j
public class ApplicationContextProvider {
    private static ApplicationContext ctx = null;  
    public static void setApplicationContext(ApplicationContext applicationContext)
            throws BeansException {
        log.info("获取applicationContext:{}",applicationContext);
        ctx = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        return ctx;
    }

    public static <T> T getBean(Class<T> type) {
        try {
            return Optional.ofNullable(ctx).orElseThrow(() -> new IllegalStateException("non in spring application context.")).getBean(type);
        } catch (Exception e) {
            return null;
        }
    }
    public static Object getBean(String beanName) {
        try {
            return Optional.ofNullable(ctx).orElseThrow(() -> new IllegalStateException("non in spring application context.")).getBean(beanName);
        } catch (Exception e) {
            return null;
        }
    }
    public static void registerBean(String beanName,Class beanClass){
        ConfigurableApplicationContext configurableApplicationContext = (ConfigurableApplicationContext) ctx;
        GenericBeanDefinition beanDefinition = (GenericBeanDefinition)configurableApplicationContext.getBeanFactory().getBeanDefinition(beanName);
        log.info("注册bean,getBeanClassName:{}",beanDefinition.getBeanClassName());
        beanDefinition.setBeanClass(beanClass);
        DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) configurableApplicationContext.getBeanFactory();
        beanFactory.registerBeanDefinition(beanName,beanDefinition);
        log.info("注册bean:{}",beanName);
    }
    public  static void removeBean(String beanName){
        ConfigurableApplicationContext configurableApplicationContext = (ConfigurableApplicationContext) ctx;
        DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) configurableApplicationContext.getBeanFactory();
        beanFactory.removeBeanDefinition(beanName);
        log.info("删除bean:{}",beanName);
    }

}
